package com.cesgroup.api.watch;

import cn.hutool.core.io.FileUtil;
import com.cesgroup.api.entity.DictionaryEntity;
import com.cesgroup.api.service.DictionaryService;
import lombok.AllArgsConstructor;
import lombok.Builder;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;

import java.io.File;

@Builder @AllArgsConstructor
public class FileListener extends FileAlterationListenerAdaptor {

	@Override // 文件创建时触发
	public void onFileCreate(final File file) {
		service.put(DictionaryEntity.CACHE_KEY, file);
	}

	@Override // 文件删除时触发
	public void onFileDelete(final File file) {
		service.clear(DictionaryEntity.CACHE_KEY);
		
		FileUtil.loopFiles(file.getParentFile()).forEach(f -> {
			if (null != f && "xml".equals(FileUtil.extName(f))) service.put(DictionaryEntity.CACHE_KEY, f);	
		});
	}

	@Override // 文件修改时触发
	public void onFileChange(final File file) {
		service.put(DictionaryEntity.CACHE_KEY, file);
	}
	
	private DictionaryService service;
}
